package com.anxpp.calculator.bio;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Random;

/**
 *  阻塞式I/O创建的客户端
 *  @author lijun
 *  @version 1.0
 */
public class Client {
    //默认的端口号
    private static int DEFAULT_SERVER_PORT = 12345;
    private static String DEFAULT_SERVER_IP = "127.0.0.1";

    public static void send(String str_expression){
        send(DEFAULT_SERVER_PORT, str_expression);
    }
    private static void send(int port, String strexpression){
        System.out.println("--------------------------------------");
        System.out.println("客户端发出的算术表达式为："+ strexpression);
        Socket socket = null;
        BufferedReader in = null;
        PrintWriter out = null;
        try{
            socket = new Socket(DEFAULT_SERVER_IP, port);
            in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            out = new PrintWriter(socket.getOutputStream(), true);
            out.println(strexpression);
            System.out.println("客户端收到的计算结果为：" + in.readLine());
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //一些必要的清理工作
            if(in != null){
                try{
                    in.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
                in = null;
            }
            if(out != null){
                out.close();
                out = null;
            }
            if(socket != null){
                try{
                    socket.close();
                }catch(IOException e){
                    e.printStackTrace();
                }
                socket = null;
            }
        }
    }

    public static void main(String [] args){
        final char operators[] = {'+', '-', '*', '/'};
        final Random random = new Random(System.currentTimeMillis());
        while(true){
            //随机产生算术表达式
            String expression = random.nextInt(10)+""+operators[random.nextInt(4)]+random.nextInt(10);
            if(!expression.contains("/0"))
                Client.send(expression);
//            try{
//                Thread.currentThread().sleep(random.nextInt(1000));
//            }catch(InterruptedException e){
//                e.printStackTrace();
//            }
        }
    }

}

